from rest_framework import serializers
from .models import Template
import json

class TemplateSerializer(serializers.ModelSerializer):
    settings = serializers.JSONField(encoder=json.JSONEncoder)
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)
    
    class Meta:
        model = Template
        fields = '__all__'
        read_only_fields = ('create_time',)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if isinstance(data['settings'], str):
            data['settings'] = json.loads(data['settings'])
        return data

    def to_internal_value(self, data):
        if 'settings' in data and not isinstance(data['settings'], str):
            data = data.copy()
            data['settings'] = json.dumps(
                data['settings'],
                ensure_ascii=False
            )
        return super().to_internal_value(data)

    def create(self, validated_data):
        return super().create(validated_data)